import { getPositions } from '@/api/common';
import { Tag, Space, Divider, Image } from 'antd-mobile';
import { useEffect, useState, useRef } from 'react';
import { DownOutline, UpOutline } from 'antd-mobile-icons';

interface ListItem {
  hasNext: boolean;
  keywordID: number;
  keywordName: string;
  parentID: number;
  sort: number;
}
type TreeItem = ListItem & { children: TreeItem[] };
function ThePositions() {
  const [listData, setListData] = useState([]);
  const loadData = async () => {
    const { data } = await getPositions({ parentID: 0, withCache: true, districtId: 0, from: 4 });
    if (data.code === 1) {
      const d = data.data || [];
      // 将数组数据根据 parentID 转换成树结构, 只取两层
      const treeList = d.reduce((acc: TreeItem[], cur: ListItem) => {
        if (cur.parentID === 0) {
          acc.push({ ...cur, children: [] });
        } else {
          acc.find((item: TreeItem) => item.keywordID === cur.parentID)?.children?.push({ ...cur, children: [] });
        }
        return acc;
      }, []);
      setListData(treeList);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  const listRefs = useRef<HTMLDivElement[]>([]);
  const [heightValue, setHeightValue] = useState('auto');
  const [isExpanded, setIsExpanded] = useState(false);
  useEffect(() => {
    // 确保有足够的数据项
    let h = 0;
    if (listData.length > 3) {
      // 遍历前三项并获取它们的高度
      for (let i = 0; i < 3; i++) {
        const offsetHeight = listRefs.current[i] ? listRefs.current[i].offsetHeight : 0;
        h += offsetHeight;
      }
      setHeightValue(`${h}px`);
    } else {
      setHeightValue('auto');
    }
  }, [listData]);

  // 行业图标对应关系
  const chartMap: { [key: number]: string } = {
    9121: '/src/assets/imgs/hy-hr.png',
    9122: '/src/assets/imgs/hy-sale.8fed608.png',
    9123: '/src/assets/imgs/hy-computer.cb274fc.png',
    9124: '/src/assets/imgs/hy-electronics.png',
    9125: '/src/assets/imgs/hy-finance.png',
    9126: '/src/assets/imgs/hy-product.png',
    9127: '/src/assets/imgs/hy-build.png',
    9128: '/src/assets/imgs/hy-trade.7500851.png',
    9129: '/src/assets/imgs/hy-chemistry.png',
    9130: '/src/assets/imgs/hy-advertisement.bb98c56.png',
    9131: '/src/assets/imgs/hy-consult.png',
    9132: '/src/assets/imgs/hy-service.8074250.png',
    9133: '/src/assets/imgs/hy-environmental.19a5b09.png',
  };

  return (
    <div className="mt-[15px] px-[12px] py-[15px] bg-white">
      <div className="overflow-hidden" style={{ height: isExpanded ? 'auto' : heightValue }}>
        {listData.map((item: TreeItem, index) => (
          <div
            className="overflow-hidden"
            ref={(el: HTMLDivElement) => (listRefs.current[index] = el)}
            key={item.keywordID}
          >
            <div className="flex items-center text-[16px] font-bold mb-[12px]">
              <Image className="h-[22px] mr-[5px]" src={chartMap[item.keywordID]} alt="" />
              <span>{item.keywordName}</span>
            </div>
            <Space wrap>
              {item.children.map((child: TreeItem) => (
                <Tag round color="#f5f7fa" className="text-[14px] text-[#333] px-[10px] py-[8px]" key={child.keywordID}>
                  {child.keywordName}
                </Tag>
              ))}
            </Space>
            <Divider style={{ display: index === listData.length - 1 ? 'none' : '' }} />
          </div>
        ))}
      </div>
      <Divider style={{ display: !isExpanded ? 'none' : '' }} />
      <div
        className="flex items-center justify-center text-[12px] text-[#999]"
        style={{ display: listData.length > 3 ? '' : 'none' }}
        onClick={() => setIsExpanded(!isExpanded)}
      >
        {isExpanded ? '收起' : '展开全部'}
        <DownOutline style={{ display: isExpanded ? 'none' : '' }} className="ml-[5px]" />
        <UpOutline style={{ display: !isExpanded ? 'none' : '' }} className="ml-[5px]" />
      </div>
    </div>
  );
}

export default ThePositions;
